<template>
  <input
    class="number-input"
    type="text"
    :value="displayValue"
    @input="onInput"
    @blur="onBlur"
    @focus="onFocus"
    :placeholder="placeholder"
    :disabled="disabled"
    :maxlength="maxLength"
  />
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: 0
  },
  min: {
    type: Number,
    default: 0
  },
  max: {
    type: Number,
    default: 999999
  },
  precision: {
    type: Number,
    default: 0 // 小数位数，0表示整数
  },
  placeholder: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  maxLength: {
    type: Number,
    default: 10
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const displayValue = ref('')
const isFocused = ref(false)

// 初始化显示值
const initDisplayValue = () => {
  const value = Number(props.modelValue) || 0
  displayValue.value = value.toString()
}

// 监听外部值变化
watch(() => props.modelValue, () => {
  if (!isFocused.value) {
    initDisplayValue()
  }
}, { immediate: true })

// 验证并格式化数字
const validateNumber = (value) => {
  // 移除所有非数字和小数点的字符
  let cleanValue = value.replace(/[^\d.]/g, '')
  
  // 如果是整数模式，移除小数点
  if (props.precision === 0) {
    cleanValue = cleanValue.replace(/\./g, '')
  } else {
    // 确保只有一个小数点
    const parts = cleanValue.split('.')
    if (parts.length > 2) {
      cleanValue = parts[0] + '.' + parts.slice(1).join('')
    }
    
    // 限制小数位数
    if (parts[1] && parts[1].length > props.precision) {
      cleanValue = parts[0] + '.' + parts[1].substring(0, props.precision)
    }
  }
  
  return cleanValue
}

// 输入处理
const onInput = (e) => {
  const inputValue = e.detail ? e.detail.value : e.target.value
  const validValue = validateNumber(inputValue)
  
  displayValue.value = validValue
  
  // 转换为数字并验证范围
  const numValue = Number(validValue) || 0
  const clampedValue = Math.max(props.min, Math.min(props.max, numValue))
  
  emit('update:modelValue', clampedValue)
}

// 失焦处理
const onBlur = () => {
  isFocused.value = false
  
  let numValue = Number(displayValue.value) || 0
  
  // 范围限制
  numValue = Math.max(props.min, Math.min(props.max, numValue))
  
  // 格式化显示
  if (props.precision > 0) {
    displayValue.value = numValue.toFixed(props.precision)
  } else {
    displayValue.value = Math.floor(numValue).toString()
  }
  
  emit('update:modelValue', numValue)
  emit('change', numValue)
}

// 聚焦处理
const onFocus = () => {
  isFocused.value = true
}

// 初始化
initDisplayValue()
</script>

<style scoped>
.number-input {
  width: 100%;
  height: 100%;
  line-height: 60rpx;
  text-align: center;
  border-radius: 4rpx;
  /* font-size: 28rpx; */
  background-color: #fff;
}

.number-input:focus {
  border-color: #007aff;
  outline: none;
}

.number-input:disabled {
  background-color: #f5f5f5;
  color: #999;
}
</style>